package com.ocean.security.handler;

import com.ocean.core.util.constants.ConstantsAttribute;
import com.ocean.core.util.response.ResultSet;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权失败
 *
 * @author zhang
 * @since 2021/9/10
 */
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        String error;
        if (e instanceof LockedException) {
            error = ConstantsAttribute.ACCOUNT_LOCKED;
        } else if (e instanceof CredentialsExpiredException) {
            error = ConstantsAttribute.PASSWORD_EXPIRED;
        } else if (e instanceof AccountExpiredException) {
            error = ConstantsAttribute.ACCOUNT_EXPIRED;
        } else if (e instanceof DisabledException) {
            error = ConstantsAttribute.ACCOUNT_DISABLE;
        } else if (e instanceof BadCredentialsException) {
            error = ConstantsAttribute.PASSWORD_ERROR;
        } else {
            error = ConstantsAttribute.NO_AUTHORIZATION;
        }
        httpServletResponse.getWriter().print(ResultSet.error(error));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
